package com.bestv.search.common.dao.hibernate;

import com.bestv.search.common.dao.SysUserDao;
import com.bestv.search.common.model.SysRole;
import com.bestv.search.common.model.SysUser;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.sql.SQLException;
import java.util.List;

public class SysUserDaoHibernate extends GenericDaoHibernate<SysUser, Long> implements SysUserDao, UserDetailsService {

    public SysUserDaoHibernate() {
        super(SysUser.class);
    }

    public SysUser getUserById(Long id) {
        return super.get(id);
    }

    @SuppressWarnings("unchecked")
    public List<SysUser> getUsers() {
        return getHibernateTemplate().find("from SysUser u where u.enable = true");
    }

    public SysUser saveUser(final SysUser user) {
        getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                session.merge(user);
                return user;
            }
        });
        return user;
    }

    @SuppressWarnings("unchecked")
    public List<SysUser> getUserByName(String name) {
        return super.getHibernateTemplate().find("from SysUser u where u.username='" + name + "'");
    }

    @SuppressWarnings("unchecked")
    public List<SysUser> getUserByRole(SysRole role) {
        return super.getHibernateTemplate().find("from SysUser where ? in roles ", role);
    }

    @SuppressWarnings("unchecked")
    public String getPasswordByLoginName(String loginName) {
        List<SysUser> list = getHibernateTemplate().find("from SysUser user where user.loginName=?", loginName);
        if (list.size() > 0) {
            SysUser user = list.get(0);
            return user.getPassword();
        }
        return "";
    }

    @SuppressWarnings("unchecked")
    public SysUser getUserByLoginName(final String loginName) {
        List<SysUser> users = super.getHibernateTemplate().find("from SysUser where loginName = ?", loginName);
        if (users.size() > 0)
            return users.get(0);
        return null;
    }

    @SuppressWarnings("unchecked")
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException, DataAccessException {
        List<SysUser> users = super.getHibernateTemplate().find("from SysUser where loginName = ?", loginName);
        if (users == null || users.isEmpty())
            throw new UsernameNotFoundException("user '" + loginName + "' not found...");
        return users.get(0);
    }
}
